// app.js

App({
  onLaunch() {
    /* wx.addInterceptor('request', {
      invoke: (args) => {
        const openid = wx.getStorageSync('openid');
        if (openid) {
          // 在请求头中添加session_id
          args.header = args.header || {};
          args.header['X-Session-ID'] = openid;
        }
        return args; // 必须返回修改后的args
      }
    });     */
    // 展示本地存储能力
    /* const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs) */

    // 登录
    // 如果本地已存储openid，跳过后台读取，直接从本地读取，并设置globalData
    /* console.log(wx.getStorageInfoSync());
    const openid = wx.getStorageSync('openid');
    const session_key = wx.getStorageSync('session_key');
    console.log('openid', openid);
    console.log('session_key', session_key);
    if (openid) {
      getApp().globalData.openid = openid;
      return;
    } */
    // 1. 调用wx.login获取code
    wx.login({
      success: (loginRes) => {
        const code = loginRes.code
        if (!code) {
          Dialog.alert({
            message: '获取code失败',
          }).then(() => {
            // on close
          });
          return
        }

        // 2. 把code传给自己的后端接口
        wx.request({          
          url: `${getApp().globalData.appServer}/wxlogin`,
          method: 'POST',
          data: {
            code: code
          }, // 传递code
          success: (res) => {
            // console.log('后端返回的openid：', res.data.obj)
            // 存储到全局或本地
            const app = getApp();
            
            app.globalData.openid = res.data.ext;
            app.globalData.userInfo = res.data.obj;
            
            
            
            // console.log('设置', wx.getStorageInfoSync());
          },
          fail: (err) => {
            wx.setStorageSync('openid', null);
            console.error('调用后端接口失败：', err)
          }
        })
      }
    })
  },
  globalData: {
    openid: null,
    userInfo: null,
    appServer: 'http://127.0.0.1:24500/wxapp'
  }
})